package com.wsz.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsz.security.pojo.Role;
import com.wsz.security.pojo.User;
import com.wsz.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDetailsServerImpl implements UserDetailsService, UserDetailsPasswordService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", s));

        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }else {
           List<Role> roles = userService.getRoleByUserId(user.getId());
           user.setRoles(roles);
        }
        return user;
    }

    @Override
    public UserDetails updatePassword(UserDetails userDetails, String newPassword) {
        int i = userService.updatebyUsername(userDetails.getUsername(),newPassword);
        if(i == 1){
            ((User) userDetails).setPassword(newPassword);
        }
        return userDetails;
    }
}
